import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:image_picker/image_picker.dart';
import 'package:ct_pa_majordomo/pages/mine/online_pay/state/online_pay_state.dart';
import 'package:ct_pa_majordomo/config/theme_vars.dart';
import 'package:ct_pa_majordomo/pages/commonApi.dart';
import 'package:ct_pa_majordomo/widgets/normal_scaffold/index.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:dio/dio.dart';
import 'package:permission_handler/permission_handler.dart';

class AccountLicensePage extends StatefulWidget {
  final OnlinePayState state;
  final VoidCallback onStateChanged;
  final bool isReadOnly;

  const AccountLicensePage({
    super.key,
    required this.state,
    required this.onStateChanged,
    this.isReadOnly = false,
  });

  @override
  State<AccountLicensePage> createState() => _AccountLicensePageState();
}

class _AccountLicensePageState extends State<AccountLicensePage> {
  late ImagePicker _imagePicker;
  XFile? _licensePhotoFile;

  @override
  void initState() {
    super.initState();
    _imagePicker = ImagePicker();
  }

  void _showImageSourceOptions() {
    bool isPickerActive = false;
    
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) => CupertinoActionSheet(
        title: const Text('选择图片来源'),
        actions: <CupertinoActionSheetAction>[
          CupertinoActionSheetAction(
            onPressed: () {
              if (isPickerActive) return;
              isPickerActive = true;
              Navigator.pop(context);
              
              Future.microtask(() {
                _takePhoto().then((_) {
                  isPickerActive = false;
                }).catchError((e) {
                  isPickerActive = false;
                  print("拍照操作错误: $e");
                });
              });
            },
            child: const Text('拍照'),
          ),
          CupertinoActionSheetAction(
            onPressed: () {
              if (isPickerActive) return;
              isPickerActive = true;
              Navigator.pop(context);
              
              Future.microtask(() {
                _pickImage().then((_) {
                  isPickerActive = false;
                }).catchError((e) {
                  isPickerActive = false;
                  print("选择图片操作错误: $e");
                });
              });
            },
            child: const Text('从相册选择'),
          ),
        ],
        cancelButton: CupertinoActionSheetAction(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text('取消'),
        ),
      ),
    );
  }

  Future<void> _takePhoto() async {
    try {
      var status = await Permission.camera.status;
      if (status.isDenied) {
        await Permission.camera.request();
      } else if (status.isGranted) {
        final picker = ImagePicker();
        final pickedImage = await picker.pickImage(
          source: ImageSource.camera,
          imageQuality: 80,
        );
        
        if (pickedImage != null && mounted) {
          setState(() {
            _licensePhotoFile = pickedImage;
          });
        }
      }
    } catch (e) {
      print("拍照错误: ${e.toString()}");
      EasyLoading.showError("拍照失败：${e.toString()}");
    }
  }

  Future<void> _pickImage() async {
    try {
      final picker = ImagePicker();
      final pickedImage = await picker.pickImage(
        source: ImageSource.gallery,
        imageQuality: 80,
      );
      
      if (pickedImage != null && mounted) {
        setState(() {
          _licensePhotoFile = pickedImage;
        });
      }
    } catch (e) {
      print("选择图片错误: ${e.toString()}");
      EasyLoading.showError("选择图片失败：${e.toString()}");
    }
  }

  Future<void> _uploadImage() async {
    try {
      EasyLoading.show(status: "上传中...");
      final file = File(_licensePhotoFile!.path);
      
      // 检查文件大小是否超过1M
      final fileSize = await file.length();
      final sizeInMB = fileSize / (1024 * 1024);
      if (sizeInMB > 1) {
        EasyLoading.dismiss();
        EasyLoading.showToast("请上传小于1M的图片");
        return;
      }

      FormData formData = FormData();
      formData.files.add(MapEntry(
        "file",
        await MultipartFile.fromFile(file.path, filename: "account_license_${DateTime.now().millisecondsSinceEpoch}.jpg")
      ));

      Map res = await commonApi.upload(formData);
      EasyLoading.dismiss();

      if (res["code"].toString() != "200") {
        EasyLoading.showError("上传失败：${res["msg"] ?? "未知错误"}");
        return;
      }

      setState(() {
        widget.state.updateCompanyAccountLicenseInfo(
          accountOpeningLicenseImg: res["data"]["url"],
        );
      });
      EasyLoading.showSuccess("上传成功");
    } catch (e) {
      EasyLoading.dismiss();
      print("上传图片错误: ${e.toString()}");
      EasyLoading.showError("上传失败：${e.toString()}");
    }
  }

  Future<void> _saveForm() async {
    // 检查是否上传了开户许可证照片
    if (widget.state.company["accountOpeningLicenseImg"].isEmpty && _licensePhotoFile == null) {
      EasyLoading.showError('请上传开户许可证照片');
      return;
    }

    EasyLoading.show(status: "保存中...");

    try {
      // 上传新图片（如果有）
      if (_licensePhotoFile != null) {
        await _uploadImage();
      }

      widget.onStateChanged();
      EasyLoading.dismiss();
      EasyLoading.showSuccess("保存成功");
      if (mounted) {
        Navigator.pop(context);
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError("保存失败：${e.toString()}");
    }
  }

  // 只读模式提示
  Widget _buildReadOnlyTip() {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.blue.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.blue.withOpacity(0.3)),
      ),
      child: Row(
        children: [
          Icon(
            Icons.info_outline,
            color: Colors.blue,
            size: 20,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              '当前信息为只读状态，无法修改',
              style: TextStyle(
                color: Colors.blue.shade700,
                fontSize: 14,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildImageUploadSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              '开户许可证照片',
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const Text(
              ' *',
              style: TextStyle(
                color: Colors.red,
                fontSize: 16,
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        GestureDetector(
          onTap: widget.isReadOnly ? null : _showImageSourceOptions,
          child: Container(
            width: double.infinity,
            height: 200,
            decoration: BoxDecoration(
              color: ThemeVars.colorBackground,
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: ThemeVars.colorBorder),
            ),
            child: widget.state.company["accountOpeningLicenseImg"].isNotEmpty || _licensePhotoFile != null
                ? ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: widget.state.company["accountOpeningLicenseImg"].isNotEmpty
                        ? Image.network(
                            widget.state.company["accountOpeningLicenseImg"],
                            fit: BoxFit.cover,
                          )
                        : Image.file(
                            File(_licensePhotoFile!.path),
                            fit: BoxFit.cover,
                          ),
                  )
                : Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Icon(Icons.add_photo_alternate_outlined, size: 50),
                      const SizedBox(height: 8),
                      const Text(
                        '点击上传开户许可证照片',
                        style: TextStyle(
                          color: ThemeVars.colorTextSec,
                        ),
                      ),
                    ],
                  ),
          ),
        ),
        const SizedBox(height: 8),
        const Text(
          '图片必须JPG/PNG/JPEG/BMP等类型文件，大小在1M以内',
          style: TextStyle(
            color: ThemeVars.colorTextSec,
            fontSize: 12,
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: '开户许可证照片',
      child: ListView(
        padding: const EdgeInsets.all(ThemeVars.paddingPage),
        children: [
          // 只读提示
          if (widget.isReadOnly) _buildReadOnlyTip(),
          _buildImageUploadSection(),
          const SizedBox(height: 24),
          // 只有在非只读模式下才显示保存按钮
          if (!widget.isReadOnly)
            SizedBox(
              width: double.infinity,
              height: 44,
              child: ElevatedButton(
                onPressed: _saveForm,
                style: ElevatedButton.styleFrom(
                  backgroundColor: ThemeVars.colorPrimary,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                child: const Text(
                  '保存',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }
} 